import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import {
  showDialog,
  showToast,
} from 'vant';

import {
  examApi,
} from '../api/modules/exam';
import type {
  IExam,
  IExamRecord,
  IExamWithPaper,
} from '../types/exam';

export const useExamStore = defineStore('exam', () => {
  // State
  const examList = ref<IExam[]>([]);
  const currentExam = ref<IExamWithPaper | null>(null);
  const examRecords = ref<IExamRecord[]>([]);
  const answers = ref<Record<string, { question_id: string; selected_answers: number[] }[]>>({});
  const examResult = ref<any>(null);
  const loading = ref(false);
  const examStarted = ref(false);
  const timeRemaining = ref(0);
  const timerInterval = ref<any>(null);
  const currentQuestionIndex = ref(0);
  const currentRecordId = ref('');

  // Getters
  const hasMoreExams = computed(() => examList.value.length > 0);
  const examInProgress = computed(() => examStarted.value && timeRemaining.value > 0);
  const questionCount = computed(() => currentExam.value?.paper?.question_list?.length || 0);
  const currentQuestion = computed(() => {
    if (!currentExam.value?.paper?.question_list) return null;
    return currentExam.value.paper.question_list[currentQuestionIndex.value];
  });
  const answeredCount = computed(() => {
    if (!answers.value || !currentExam.value?._id) return 0;
    const examAnswers = answers.value[currentExam.value._id] || [];
    return examAnswers.filter(answer => 
      answer && 
      answer.selected_answers && 
      answer.selected_answers.length > 0
    ).length;
  });
  const formattedTimeRemaining = computed(() => {
    const minutes = Math.floor(timeRemaining.value / 60);
    const seconds = timeRemaining.value % 60;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  });

  // Actions
  const fetchExamList = async () => {
    loading.value = true;
    try {
      const response = await examApi.getExamList();

      console.log('fetchExamList 响应:', response);
      console.log('考试列表数据:', response.data?.list);

      // 根据新的 API 响应结构获取数据
      examList.value = response.data?.list || [];

      // 调试每个考试项目的 _id
      examList.value.forEach((exam, index) => {
        console.log(`考试 ${index}:`, { _id: exam._id, exam_name: exam.exam_name });
      });

      return Promise.resolve(response);
    } catch (error: any) {
      console.error('Store 中获取考试列表失败:', error);
      showToast(error.message || '获取考试列表失败');
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const fetchExamDetail = async (examId: string) => {
    console.log('fetchExamDetail Store 调用:', { examId });
    
    loading.value = true;
    try {
      const response = await examApi.getExamDetail(examId);
      currentExam.value = response.data;
      return Promise.resolve(response);
    } catch (error: any) {
      console.error('Store 中获取考试详情失败:', error);
      showToast(error.message || '获取考试详情失败');
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const startExam = async (examId: string) => {
    loading.value = true;
    try {
      const response = await examApi.startExam(examId);
      // 从响应中提取考试信息
      currentExam.value = response.data.activity;
      currentRecordId.value = response.data.record_id;
      examStarted.value = true;
      currentQuestionIndex.value = 0;
      
      // 初始化答案数组
      if (!answers.value[examId]) {
        answers.value[examId] = Array(questionCount.value).fill(null).map((_, index) => ({
          question_id: currentExam.value!.paper!.question_list![index]._id,
          selected_answers: []
        }));
      }
      
      // 设置考试时间
      if (currentExam.value?.paper?.duration) {
        timeRemaining.value = currentExam.value.paper.duration * 60;
        startTimer();
      }
      
      return Promise.resolve(response);
    } catch (error: any) {
      showToast(error.message || '开始考试失败');
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const startTimer = () => {
    if (timerInterval.value) clearInterval(timerInterval.value);
    
    timerInterval.value = setInterval(() => {
      if (timeRemaining.value <= 0) {
        endExam(true);
        return;
      }
      
      timeRemaining.value--;
      
      // 自动保存答案 - 暂时禁用，避免404错误
      // if (timeRemaining.value % 30 === 0) {
      //   saveAnswers();
      // }
      
      // 时间提醒
      if (timeRemaining.value === 300) { // 5分钟
        showToast('距离考试结束还有5分钟');
      } else if (timeRemaining.value === 60) { // 1分钟
        showToast('距离考试结束还有1分钟');
      }
    }, 1000);
  };

  const stopTimer = () => {
    if (timerInterval.value) {
      clearInterval(timerInterval.value);
      timerInterval.value = null;
    }
  };

  const saveAnswers = async () => {
    // 暂时禁用自动保存功能，因为后端没有相应接口
    // 答案会在最终提交时保存
    return;
    
    /* 
    const exam = currentExam.value;
    if (!exam || !exam._id) return;
    
    try {
      await examApi.saveExamAnswer({
        exam_id: exam._id,
        answers: answers.value[exam._id] || []
      });
    } catch (error) {
      console.error('保存答案失败', error);
    }
    */
  };

  const endExam = async (isTimeout = false) => {
    stopTimer();
    
    if (isTimeout) {
      showToast('考试时间已结束');
    }
    
    if (!currentExam.value?._id) return;
    
    // 确认提交
    if (!isTimeout) {
      const unanswered = questionCount.value - answeredCount.value;
      if (unanswered > 0) {
        try {
          await showDialog({
            title: '提交确认',
            message: `您还有 ${unanswered} 题未作答，确定要提交吗？`,
            confirmButtonText: '确定提交',
            cancelButtonText: '继续答题'
          });
        } catch (e) {
          return; // 取消提交
        }
      }
    }
    
    loading.value = true;
    try {
      console.log('准备提交考试 - Store 调试:', {
        record_id: currentRecordId.value,
        answers: answers.value[currentExam.value._id],
        is_timeout: isTimeout
      });
      
      const response = await examApi.submitExamRecord({
        record_id: currentRecordId.value,
        answers: answers.value[currentExam.value._id] || [],
        is_timeout: isTimeout
      });
      
      console.log('提交考试成功 - 响应:', response);
      console.log('响应数据:', response.data);
      
      examResult.value = response.data;
      examStarted.value = false;
      return Promise.resolve(response);
    } catch (error: any) {
      console.error('Store 中提交考试失败:', error);
      showToast(error.message || '提交考试失败');
      return Promise.reject(error);
    } finally {
      loading.value = false;
    }
  };

  const setAnswer = (questionIndex: number, answer: number[]) => {
    if (!currentExam.value?._id || !currentExam.value?.paper?.question_list) return;
    
    const examId = currentExam.value._id;
    const question = currentExam.value.paper.question_list[questionIndex];
    
    if (!question) return;
    
    if (!answers.value[examId]) {
      answers.value[examId] = Array(questionCount.value).fill(null).map((_, index) => ({
        question_id: currentExam.value!.paper!.question_list![index]._id,
        selected_answers: []
      }));
    }
    
    // 更新指定题目的答案
    answers.value[examId][questionIndex] = {
      question_id: question._id,
      selected_answers: answer
    };
  };

  const goToQuestion = (index: number) => {
    if (index >= 0 && index < questionCount.value) {
      currentQuestionIndex.value = index;
    }
  };

  const nextQuestion = () => {
    if (currentQuestionIndex.value < questionCount.value - 1) {
      currentQuestionIndex.value++;
    }
  };

  const prevQuestion = () => {
    if (currentQuestionIndex.value > 0) {
      currentQuestionIndex.value--;
    }
  };

  const resetExamState = () => {
    examStarted.value = false;
    timeRemaining.value = 0;
    stopTimer();
    currentQuestionIndex.value = 0;
  };

  return {
    // State
    examList,
    currentExam,
    examRecords,
    answers,
    examResult,
    loading,
    examStarted,
    timeRemaining,
    timerInterval,
    currentQuestionIndex,
    currentRecordId,
    
    // Getters
    hasMoreExams,
    examInProgress,
    questionCount,
    currentQuestion,
    answeredCount,
    formattedTimeRemaining,
    
    // Actions
    fetchExamList,
    fetchExamDetail,
    startExam,
    startTimer,
    stopTimer,
    saveAnswers,
    endExam,
    setAnswer,
    goToQuestion,
    nextQuestion,
    prevQuestion,
    resetExamState
  };
});
